<template>
  <div class="home">

    <button @click="addItem">新增</button>
    <test-list :data="list">
      <test-item label="序号" prop="id"/>
      <test-item label="姓名" prop="name"/>
      <test-item label="性别" prop="sex">
        <template v-slot="scope">
          {{['男','女'][scope.row.sex - 1]}}
        </template>
      </test-item>
      <test-item label="操作">
        <template v-slot="scope">
          <button @click="look(scope.row)">查看</button>
          <button @click="deleteItem(scope.row)">删除</button>
        </template>
      </test-item>
    </test-list>
    
  </div>
</template>


<script>
import TestItem from "@/components/Table/TableItem";
export default {
  name: 'HomeView',
  components: {TestItem},
  data(){
    return {
      // 后端来的数据
      list: [
        {
          id: 1,
          name: 'abc',
          sex: '1'
        },
        {
          id: 2, 
          name: 'def',
          sex: '2'
        },
        {
          id: 3,
          name: 'ghj',
          sex: '2'
        },
        {
          id: 4,
          name: 'kke',
          sex: '1'
        },
        {
          id: 6,
          name: 'ab',
          sex: '1'
        },
        {
          id:9,
          name: 'def',
          sex: '2'
        },
        {
          id: 8,
          name: 'ghj',
          sex: '2'
        },
        {
          id: 12,
          name: 'kke',
          sex: '1'
        }
      ]
    }
  },
  methods:{
    look(row){
      alert(JSON.stringify(row))
    },
    deleteItem(row){
      this.list.splice(this.list.findIndex(item=>item.id === row.id), 1)
    },
    addItem(){
      this.list.push({
        id: this.list[this.list.length - 1].index += 5,
        name: this.randomChinese(3),
        sex:'2'
      })
    },
    // 随机生成汉字
    randomChinese(length){ 
      let start = "4E00";   
      let end = "9FA5";
      let str = "";
      let max = parseInt(end, 16) - parseInt(start, 16);
      for (let i = 0; i < length; i++) {
        let random = (Math.floor(Math.random() * max) + parseInt(start, 16)).toString(16);
        str = unescape(`%u${random}`) + str
      }
      return str;
    }
  }
}
</script>

<style>
.a{
  display: flex;
  justify-content: center;
}
</style>
